// miniprogram/pages/picture/pictureIdtt/pictureIdtt.js
const db = wx.cloud.database()
const picture_db = db.collection('picture')
var util = require('../../../libs/util.js');
import resource from '../../../libs/resource.js'

Page({
  data: {
    imageSrc: '',
    pictureInfo: [],
    head_image: resource.picture_head_image,
    error_code: '',
    error_msg: '',
    answer: {
      texts: [],
      ans_list: [],
      img_path: "",
      answer_path: "",
      points_range: "",
      points_threshold: ""
    }
  },
  onLoad: function (options) {
    this.setData({
      onling: getApp().globalData.onling,
    })
    if (this.data.onling) return
    wx.setNavigationBarTitle({
      title: '图片识别'
    })
  },
  onShareAppMessage: function () {

  },
  //上传图片
  _chooseImage: function (event) {
    var _this = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        console.log("照片信息：", res)
        console.log("tempFilePaths", tempFilePaths)
        _this.setData({
          imageSrc: tempFilePaths[0],
          pictureInfo: []
        })
        wx.showLoading({
          title: '正在识别中...',
        })
        _this.getPictureInfoDb(tempFilePaths[0])
      }
    })
  },
  //从数据库获取照片信息
  getPictureInfoDb(tempFilePath) {
    picture_db.where({
      // filePath: tempFilePath.substring(72)
      filePath: tempFilePath
    }).get().then(res => {
      var picture_info = res.data
      console.log("获取数据库-照片信息：", picture_info)
      if (picture_info.length != 0) {
        var pictureObj = JSON.parse(picture_info[0].result)
        wx.hideLoading()
        this.setData({
          pictureInfo: pictureObj.result,
        })
      } else {
        this.getPictureBase64(tempFilePath);
      }
    })
  },
  //获取base64
  getPictureBase64(tempFilePath) {
    var _this = this
    wx.getFileSystemManager().readFile({
      filePath: tempFilePath, //选择图片返回的相对路径
      encoding: "base64", //这个是很重要的
      success: res => { //成功的回调
        //返回base64格式
        // console.log('data:image/png;base64,' + res.data)
        _this.getPictureInfoNet(tempFilePath, res.data)
      },
      // fail: wx.hideLoading()
    })
  },
  //识别图片
  getPictureInfoNet: function (tempFilePath, str64) {
    var _this = this
    wx.cloud.callFunction({
      name: 'picture',
      data: {
        str64: str64
      },
      success: function (res) {
        console.log(res)
        wx.hideLoading()
        // res.filePath = tempFilePath.substring(72)
        res.filePath = tempFilePath
        _this.save_picture_info_db(res)
        var infoObj = JSON.parse(res.result)
        var error_code = infoObj.error_code ? infoObj.error_code : ''
        var error_msg = infoObj.error_msg ? infoObj.error_msg : ''
        _this.setData({
          pictureInfo: infoObj.result,
          error_code: error_code,
          error_msg: error_msg
        })
      },
      // fail: wx.hideLoading()
    })
  },
  //保存照片信息到数据库
  save_picture_info_db(pictureObj) {
    var time = util.formatDateTime(new Date())
    time = time.split(' ')[0]
    pictureObj.date_time = time
    picture_db.add({
      data: pictureObj,
      success: function (res) {
        console.log('保存照片信息到数据库成功', res)
      },
      fail: console.error
    })
  },
  _choosePicture() {
    let _this = this
    wx.showLoading({
      title: '上传中...'
    })
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: 'https://zhaoyj.work/poetry/upload_img/', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'image_input',
          success(res) {
            console.log("uploadFile===", res)
            if (res.statusCode === 200) {
              let result = JSON.parse(res.data)
              result = result.data
              _this.setData({
                answer: {...result, ans_list: result.answers}
              })
              console.log("result", result)
            } else {
              wx.showToast({title: "识别异常!", icon: 'none'})
            }
            wx.hideLoading({})
          },
          fail(res) {
            wx.showToast({title: "上传失败!", icon: 'none'})
            wx.hideLoading({})
          }
        })
      },
      fail() {
        wx.hideLoading()
      }
    })
  },
})
// let answers1=[[1,"A"],[3,"B"],[2,"C"]]
// answers1.sort((a, b) => a[0] - b[0]);
